<template>
  <div class="translations-view">
    <div class="view-header">
      <h2>词条管理</h2>
      <div>
        <el-select v-model="selectedProductId" placeholder="选择产品" @change="loadTranslations" style="width: 200px; margin-right: 10px;">
          <el-option v-for="product in products" :key="product._id" :label="product.name" :value="product._id" />
        </el-select>
        <el-button type="primary" @click="showCreateDialog" :disabled="!selectedProductId">
          <el-icon><Plus /></el-icon>
          创建词条
        </el-button>
      </div>
    </div>

    <el-table :data="translations" style="width: 100%" v-loading="loading">
      <el-table-column prop="key" label="词条键" width="200" />
      <el-table-column prop="namespace" label="命名空间" width="150" />
      <el-table-column label="翻译" min-width="300">
        <template #default="scope">
          <el-tag v-for="[locale, value] in Object.entries(scope.row.locales)" :key="locale" style="margin-right: 10px;">
            <strong>{{ locale }}:</strong> {{ value }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button size="small" @click="editTranslation(scope.row)">编辑</el-button>
          <el-button size="small" type="success" @click="approveTranslation(scope.row)" v-if="scope.row.status === 'pending'">
            审核通过
          </el-button>
          <el-button size="small" type="warning" @click="publishTranslation(scope.row)" v-if="scope.row.status === 'approved'">
            发布
          </el-button>
          <el-button size="small" type="danger" @click="deleteTranslation(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建/编辑词条对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editingTranslation ? '编辑词条' : '创建词条'" width="700px">
      <el-form :model="currentTranslation" label-width="100px">
        <el-form-item label="词条键" required>
          <el-input v-model="currentTranslation.key" placeholder="例如: nav.home" :disabled="!!editingTranslation" />
        </el-form-item>
        <el-form-item label="命名空间">
          <el-input v-model="currentTranslation.namespace" placeholder="例如: common" />
        </el-form-item>
        
        <!-- 快速创建模式：只输入中文，自动翻译 -->
        <el-form-item v-if="!editingTranslation" label="快速创建">
          <el-switch 
            v-model="quickCreateMode" 
            active-text="仅输入中文，自动生成其他语言"
            @change="onQuickCreateModeChange"
          />
        </el-form-item>
        
        <template v-if="quickCreateMode && !editingTranslation">
          <!-- 快速创建模式 -->
          <el-form-item label="中文内容" required>
            <el-input
              v-model="chineseText"
              type="textarea"
              :rows="3"
              placeholder="输入中文翻译..."
              @blur="handleChineseInput"
            />
          </el-form-item>
          <el-form-item label="自动翻译">
            <el-button 
              type="primary" 
              @click="autoTranslateAll" 
              :loading="translating"
              :disabled="!chineseText"
            >
              <el-icon><Refresh /></el-icon>
              {{ translating ? '翻译中...' : '自动生成所有语言' }}
            </el-button>
            <el-text type="info" style="margin-left: 10px; font-size: 12px;">
              将自动翻译到：{{ targetLocalesText }}
            </el-text>
          </el-form-item>
        </template>
        
        <!-- 完整编辑模式 -->
        <el-form-item v-if="!quickCreateMode || editingTranslation" label="翻译内容" required>
          <div v-for="locale in selectedProductLocales" :key="locale" style="margin-bottom: 10px;">
            <el-input
              v-model="currentTranslation.locales[locale]"
              :placeholder="`${getLocaleDisplayName(locale)} 翻译`"
              :prefix-icon="getLocaleIcon(locale)"
            >
              <template #append v-if="!editingTranslation && locale === defaultLocale && currentTranslation.locales[locale]">
                <el-button @click="translateFromChinese(locale)" :loading="translating">
                  生成其他语言
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTranslation" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import api from '../api'

const products = ref([])
const translations = ref([])
const loading = ref(false)
const selectedProductId = ref('')
const editDialogVisible = ref(false)
const editingTranslation = ref(null)
const saving = ref(false)
const translating = ref(false)
const quickCreateMode = ref(true)
const chineseText = ref('')

const selectedProductLocales = computed(() => {
  const product = products.value.find(p => p._id === selectedProductId.value)
  return product?.supportedLocales || ['zh-CN', 'en-US']
})

const defaultLocale = computed(() => {
  const product = products.value.find(p => p._id === selectedProductId.value)
  return product?.defaultLocale || 'zh-CN'
})

const targetLocales = computed(() => {
  return selectedProductLocales.value.filter(locale => locale !== defaultLocale.value)
})

const targetLocalesText = computed(() => {
  return targetLocales.value.join(', ')
})

const currentTranslation = ref({
  key: '',
  namespace: 'common',
  locales: {}
})

const loadProducts = async () => {
  try {
    const result = await api.get('/products')
    products.value = result.data || []
    if (products.value.length > 0 && !selectedProductId.value) {
      selectedProductId.value = products.value[0]._id
      loadTranslations()
    }
  } catch (error) {
    ElMessage.error('加载产品列表失败')
  }
}

const loadTranslations = async () => {
  if (!selectedProductId.value) return
  
  loading.value = true
  try {
    const result = await api.get(`/translations?productId=${selectedProductId.value}`)
    translations.value = (result.data || []).map(t => ({
      ...t,
      locales: typeof t.locales === 'object' ? t.locales : {}
    }))
  } catch (error) {
    ElMessage.error('加载词条列表失败')
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  editingTranslation.value = null
  quickCreateMode.value = true
  chineseText.value = ''
  currentTranslation.value = {
    key: '',
    namespace: 'common',
    locales: {}
  }
  // 初始化所有语言的空值
  selectedProductLocales.value.forEach(locale => {
    currentTranslation.value.locales[locale] = ''
  })
  editDialogVisible.value = true
}

const onQuickCreateModeChange = (val) => {
  if (!val) {
    // 退出快速创建模式，保持当前已输入的内容
    if (chineseText.value && defaultLocale.value) {
      currentTranslation.value.locales[defaultLocale.value] = chineseText.value
    }
  } else {
    // 进入快速创建模式
    chineseText.value = currentTranslation.value.locales[defaultLocale.value] || ''
  }
}

const handleChineseInput = () => {
  if (chineseText.value && defaultLocale.value) {
    currentTranslation.value.locales[defaultLocale.value] = chineseText.value
  }
}

// 自动翻译所有语言
const autoTranslateAll = async () => {
  if (!chineseText.value || !chineseText.value.trim()) {
    ElMessage.warning('请先输入中文内容')
    return
  }

  translating.value = true
  try {
    const response = await api.post('/translations/auto-translate', {
      text: chineseText.value,
      fromLocale: defaultLocale.value,
      toLocales: targetLocales.value
    })

    // 填充翻译结果
    currentTranslation.value.locales[defaultLocale.value] = chineseText.value
    Object.entries(response.data).forEach(([locale, translated]) => {
      currentTranslation.value.locales[locale] = translated
    })

    ElMessage.success('自动翻译完成！')
  } catch (error) {
    ElMessage.error('自动翻译失败: ' + (error.response?.data?.message || error.message))
    // 翻译失败时至少保存中文
    if (defaultLocale.value) {
      currentTranslation.value.locales[defaultLocale.value] = chineseText.value
    }
  } finally {
    translating.value = false
  }
}

// 从中文翻译到其他语言
const translateFromChinese = async (sourceLocale) => {
  const sourceText = currentTranslation.value.locales[sourceLocale]
  if (!sourceText || !sourceText.trim()) {
    ElMessage.warning('请先输入中文内容')
    return
  }

  translating.value = true
  try {
    const response = await api.post('/translations/auto-translate', {
      text: sourceText,
      fromLocale: sourceLocale,
      toLocales: targetLocales.value
    })

    // 填充翻译结果（不覆盖已存在的内容）
    Object.entries(response.data).forEach(([locale, translated]) => {
      if (!currentTranslation.value.locales[locale] || currentTranslation.value.locales[locale] === '') {
        currentTranslation.value.locales[locale] = translated
      }
    })

    ElMessage.success('翻译完成！')
  } catch (error) {
    ElMessage.error('翻译失败: ' + (error.response?.data?.message || error.message))
  } finally {
    translating.value = false
  }
}

const editTranslation = (translation) => {
  editingTranslation.value = translation
  currentTranslation.value = {
    key: translation.key,
    namespace: translation.namespace,
    locales: { ...translation.locales }
  }
  editDialogVisible.value = true
}

const saveTranslation = async () => {
  if (!currentTranslation.value.key) {
    ElMessage.warning('请填写词条键')
    return
  }

  // 如果是快速创建模式，确保中文已填充
  if (quickCreateMode.value && !editingTranslation.value) {
    if (chineseText.value && defaultLocale.value) {
      currentTranslation.value.locales[defaultLocale.value] = chineseText.value
    }
    
    // 如果没有其他语言翻译，使用自动翻译
    const hasOtherTranslations = targetLocales.value.some(
      locale => currentTranslation.value.locales[locale] && currentTranslation.value.locales[locale].trim()
    )
    
    if (!hasOtherTranslations && chineseText.value) {
      ElMessageBox.confirm(
        '检测到只输入了中文，是否自动翻译到其他语言？',
        '提示',
        {
          confirmButtonText: '是，自动翻译',
          cancelButtonText: '否，直接保存',
          type: 'info'
        }
      ).then(async () => {
        await autoTranslateAll()
        await doSave()
      }).catch(() => {
        doSave()
      })
      return
    }
  }

  await doSave()
}

const doSave = async () => {
  saving.value = true
  try {
    // 过滤掉空值
    const locales = {}
    Object.entries(currentTranslation.value.locales).forEach(([locale, value]) => {
      if (value && value.trim()) {
        locales[locale] = value
      }
    })

    if (Object.keys(locales).length === 0) {
      ElMessage.warning('至少需要提供一个语言的翻译')
      saving.value = false
      return
    }

    const data = {
      key: currentTranslation.value.key,
      namespace: currentTranslation.value.namespace,
      productId: selectedProductId.value,
      locales
    }
    
    if (editingTranslation.value) {
      // 更新
      await api.put(`/translations/${editingTranslation.value._id}`, data)
      ElMessage.success('词条更新成功')
    } else {
      // 创建 - 如果有中文且需要自动翻译
      if (quickCreateMode.value && chineseText.value && targetLocales.value.length > 0) {
        // 使用自动翻译功能创建
        const autoTranslateData = {
          ...data,
          autoTranslate: true,
          sourceText: chineseText.value,
          sourceLocale: defaultLocale.value,
          locales: {} // 自动翻译会生成
        }
        await api.post('/translations', autoTranslateData)
        ElMessage.success('词条创建成功（已自动翻译）')
      } else {
        await api.post('/translations', data)
        ElMessage.success('词条创建成功')
      }
    }
    
    editDialogVisible.value = false
    loadTranslations()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.message || error.message))
  } finally {
    saving.value = false
  }
}

const approveTranslation = async (translation) => {
  try {
    await api.put(`/translations/${translation._id}`, { status: 'approved' })
    ElMessage.success('审核通过')
    loadTranslations()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const publishTranslation = async (translation) => {
  try {
    await api.put(`/translations/${translation._id}`, { status: 'published' })
    ElMessage.success('发布成功')
    loadTranslations()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteTranslation = async (translation) => {
  try {
    await ElMessageBox.confirm(`确定要删除词条 "${translation.key}" 吗？`, '提示', {
      type: 'warning'
    })
    await api.delete(`/translations/${translation._id}`)
    ElMessage.success('删除成功')
    loadTranslations()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const getStatusType = (status) => {
  const map = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    published: ''
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    draft: '草稿',
    pending: '待审核',
    approved: '已通过',
    published: '已发布'
  }
  return map[status] || status
}

const getLocaleIcon = (locale) => {
  return ''
}

const getLocaleDisplayName = (locale) => {
  const names = {
    'zh-CN': '简体中文',
    'zh-TW': '繁体中文',
    'en-US': '英文',
    'fr-FR': '法语',
    'ja-JP': '日语',
    'ko-KR': '韩语',
    'de-DE': '德语',
    'es-ES': '西班牙语',
    'ru-RU': '俄语',
    'pt-BR': '葡萄牙语'
  }
  return names[locale] || locale
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.translations-view {
  padding: 20px;
}

.view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-header h2 {
  margin: 0;
}
</style>

